<template>
  <div class="map-container">
    <div id="vue-openlayers"></div>
    <div class="resultSidebar" :class="{ 'hidden': !showResultSidebar }">
      <span class="close-icon" @click="closeResultSidebar">&times;</span>
      <div class="table-container">
        <Queryshow></Queryshow>
      </div>
    </div>
  </div>
</template>

<script>
import Queryshow from './Queryshow';
import "ol/ol.css";
import { Map, View } from "ol";
import Feature from 'ol/Feature';
import { Tile, Image, Vector as VectorLayer, Group } from 'ol/layer';
import {Point, LineString, Polygon} from 'ol/geom'
import { XYZ, ImageWMS, WMTS, Vector as VectorSource, OSM} from 'ol/source';
import { defaults, ScaleLine, ZoomSlider, MousePosition, OverviewMap, FullScreen } from 'ol/control';
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import {Projection} from 'ol/proj';
import { EventBus } from '../../EventBus';
import Draw from 'ol/interaction/Draw';

import GeoJSON from 'ol/format/GeoJSON';
import axios from 'axios';
import { Style, Fill, Stroke } from 'ol/style';

export default {
  components: {
    Queryshow
  },
  data() {
    return {
      map: null,
      map_vec: null,
      map_cva: null,
      showResultSidebar: false,
      drawInteraction: null,
      vectorLayer: null,
      vectorSource: null,
      wfsLayer: null,  // 用于存储WFS图层
      wfsSource: null, // 用于存储WFS数据源
      additionalLayers: [], // 存储额外的图层
      layerGroup: new Group({
      layers: [],
    }),
    };
  },
  mounted() {
    this.map_vec = new Tile({
      source: new XYZ({
        url: "http://t3.tianditu.gov.cn/DataServer?T=vec_w&tk=4cb0af3ca20c00723447448d503f404e&x={x}&y={y}&l={z}"
      }),
      visible: true,
    });
    this.map_cva = new Tile({
      source: new XYZ({
        url: "http://t3.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=4cb0af3ca20c00723447448d503f404e",
      }),
      visible: true,
    });
    // 初始化 GeoServer 矢量图层
    const geoServerVectorLayer = new VectorLayer({
      source: new VectorSource({
        format: new GeoJSON(),
        url: function() {
          // return 'https://sso.gzrhcloud.cn/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Aguizhou_area&maxFeatures=50&outputFormat=application%2Fjson';
          // return 'https://gaofei.gzrhcloud.cn/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Aguizhou_area&maxFeatures=50&outputFormat=application%2Fjson';
          return 'http://localhost:8090/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Aguizhou_area&maxFeatures=50&outputFormat=application%2Fjson';
        },
      }),
      style: new Style({
        stroke: new Stroke({
          color: 'rgba(255, 255, 0, 1.0)',
          width: 2
        }),
        
      })
    });
    this.map = new Map({
      target: 'vue-openlayers',
      layers: [this.map_vec, this.map_cva],
      controls: defaults({
        attributionOptions: {
          collapsible: false,
        },
      }).extend([
        new ScaleLine(),
        new ZoomSlider(),
        new MousePosition(),
        new FullScreen(),
        new OverviewMap({
          collapsed: false,
        }),
      ]),
      view: new View({
        center: [106.5, 26.65],
        zoom: 8,
        minZoom: 6,
        maxZoom: 18,
        projection: "EPSG:4326",
      }),
    });
    this.map.addLayer(geoServerVectorLayer);
    EventBus.$on('update-show-result-sidebar', (value) => {
      this.showResultSidebar = value;
    });
    // 初始化矢量图层和绘制交互
    this.vectorSource = new VectorSource();
    this.vectorLayer = new VectorLayer({
      source: this.vectorSource,
    });
    this.map.addLayer(this.vectorLayer);
    // 监听开始绘制事件
    EventBus.$on('start-drawing', ({ drawType }) => {
      // 清空之前的绘制
      this.clearDrawing();
      // 根据绘制类型执行相应的绘制逻辑
      switch (drawType) {
        case 'Point':
        case 'LineString':
        case 'Polygon':
        case 'Circle':
        case 'Extent':
          this.drawInteraction = new Draw({
            type: drawType,
            source: this.vectorSource,
          });
          this.drawInteraction.on('drawend', (event) => {
            this.handleDrawnFeature(event.feature, drawType);
          });
          this.map.addInteraction(this.drawInteraction);
          break;
        default:
          console.error(`Unsupported draw type: ${drawType}`);
          break;
      }
    });
     // 监听鼠标双击事件
  const mapContainer = document.getElementById('vue-openlayers');
  mapContainer.addEventListener('dblclick', this.handleMapDoubleClick);

  EventBus.$on('switch-change', this.handleSwitchChange);
  EventBus.$on('queryshow-switch-change', this.handleQueryshowSwitchChange);
    // 初始化 WFS 数据源和图层
    this.wfsSource = new VectorSource();
    this.wfsLayer = new VectorLayer({
      source: this.wfsSource,
    });
    this.map.addLayer(this.wfsLayer);
    
    // 定义样式函数
    const styleFunction = function(feature) {
    // 获取要素的颜色属性
    // const color = feature.get('color');

    // 返回样式
    return new Style({
      fill: new Fill({
      color: 'rgba(250, 250, 247, 0.5)'
        }),
      stroke: new Stroke({
        color: 'rgb(255, 152, 150)',
        width: 3
          })
        });
      };
    // 为 wfsLayer 设置样式函数
    this.wfsLayer.setStyle(styleFunction);

  },
  methods: {
    clearWfsSource() {
      if (this.wfsSource) {
        this.wfsSource.clear();
      }
    },
    closeResultSidebar() {
      this.showResultSidebar = false;
      this.wfsSource.clear(); // 清除所有WFS要素
      EventBus.$emit('close-result-sidebar');
    },
    clearDrawing() {
      // 清空之前的绘制
      if (this.drawInteraction) {
        this.map.removeInteraction(this.drawInteraction);
        this.drawInteraction = null;
      }
      // 清空矢量图层
      this.vectorSource.clear();
    },
    handleDrawnFeature(feature, drawType) {
      // 提取绘制要素的相关信息
      const geometry = feature.getGeometry();
      let featureInfo = {};

      switch (drawType) {
        case 'Point':
          featureInfo = {
            type: drawType,
            coordinates: geometry.getCoordinates(),
          };
          break;
        case 'LineString':
        case 'Polygon':
          featureInfo = {
            type: drawType,
            coordinates: geometry.getCoordinates(),
          };
          break;
        case 'Circle':
          featureInfo = {
            type: drawType,
            coordinates: geometry.getCenter(), // 使用 getCenter() 获取 Circle 的中心坐标
            radius: geometry.getRadius(), // 获取 Circle 的半径信息（如果需要）
          };
          break;
        case 'Extent':
      // 处理 Extent 的方式（如果需要）
          break;
        default:
          console.error(`Unsupported draw type: ${drawType}`);
          return;
      }

      // 通过事件总线传递绘制的要素信息给 Sidebar 组件
      EventBus.$emit('drawn-feature', featureInfo);
    },
    handleMapDoubleClick() {
    // 双击鼠标后取消绘制
    if (this.drawInteraction) {
      this.map.removeInteraction(this.drawInteraction);
      this.drawInteraction = null;
      }
    },
    handleSwitchChange({ productid, switchValue }) {
          if (switchValue) {
            this.loadWFSFeature(productid);
          } else {
        this.removeWFSFeature(productid);
          }
        },
    handleQueryshowSwitchChange({ productid, switchValue }) {
      if (!switchValue) {
        this.removeWFSFeature(productid);
      }
    },
    loadWFSFeature(productid) {
      // const wfsUrl = `https://sso.gzrhcloud.cn/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Agf&cql_filter=productid=${productid}&outputFormat=application/json`;
      // const wfsUrl = `https://gaofei.gzrhcloud.cn/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Agf&cql_filter=productid=${productid}&outputFormat=application/json`;
      const wfsUrl = `https://localhost:8090/geoserver/shp/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=shp%3Agf&cql_filter=productid=${productid}&outputFormat=application/json`;

      axios.get(wfsUrl)
        .then(response => {
          // console.log('Response:', response.data);
          if (typeof response.data === 'string' && response.data.startsWith('<?xml')) {
            console.error('Received XML error response:', response.data);
            return;
          }
          const features = new GeoJSON().readFeatures(response.data);
          this.wfsSource.addFeatures(features);
        })
        .catch(error => {
          console.error('Error loading WFS feature:', error);
        });
    },
    removeWFSFeature(productid) {
      const featuresToRemove = this.wfsSource.getFeatures().filter(feature => feature.get('productid') === productid);
      featuresToRemove.forEach(feature => this.wfsSource.removeFeature(feature));
    },
  },
    // 在组件的 created 钩子中监听事件
   created() {
    // 监听清除 wfsSource 图层的事件
    EventBus.$on('clear-wfsSource', () => {
      this.clearWfsSource();
    });
    EventBus.$on('switch-change', this.handleSwitchChange);
    EventBus.$on('queryshow-switch-change', this.handleQueryshowSwitchChange);
  },
  destroyed() {
    EventBus.$off('switch-change', this.handleSwitchChange);
    EventBus.$off('queryshow-switch-change', this.handleQueryshowSwitchChange);
  },
}
</script>

<style scoped>
.map-container {
    margin: 0;
    padding: 0;
    display: flex;
}
#vue-openlayers {
		width: 98%;
		height: 75vh;
		margin: 0px auto;
    /* margin-top: 0px;
    margin-bottom: 0px;
    margin-left: 50px;
    margin-right: 10px; */
		border: 1px solid #faf605;
        /* text-align:right */
	}
.resultSidebar {
    width: 31%; /* 设置右侧侧边栏的宽度 */
    height: 75vh; /* 与地图容器高度一致 */
    background-color: #f0f0f0;
    margin-left: 5px;
    /* 可以添加其他样式，例如背景色等 */
}
.hidden {
    display: none;
}
.close-icon {
  position: absolute;
  /* top: 12vh; */
  right: 28px;
  font-size: 22px;
  cursor: pointer;
}
.table-container {
  margin-top: 20px; /* 根据需要调整垂直偏移量 */
}
</style>